package cource.FinalExam;


import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;


/**
 * @author zeng
 * @data 2021/05/16 20:52
 */

public class BinarySeekThread extends Thread {
    private Integer[] arr;
    private int key;
    //    String starttime;
//    String endtime;
    Date starttime;
    Date endtime;
    String flag;
    String gaptime;
    int Count;

    public BinarySeekThread(Integer[] arr, int key) {
        this.arr = arr;
        this.key = key;
        this.flag = "false";
        this.gaptime = null;
    }

    @Override
    public void run() {
        //开始时间，时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss:SS");
        //写入文件数据并设置数组
//        BufferedReader bf = null;
//        //设置集合接收数据
//        HashSet<Integer> list = new HashSet<>();
//        try {
//            bf = new BufferedReader(new FileReader(new File(filename)));
//            //接收读取的字符
//            String str = null;
//            while((str = bf.readLine()) != null){
//                list.add(Integer.parseInt(str.replaceAll("\\s*", "")));//转化为数字
//            }
//            //转换为数组并排序
//            Integer[] arr = new Integer[list.size()];
//            list.toArray(arr);
//            Arrays.sort(arr);
//            this.starttime = simpleDateFormat.format(new Date());
//            //进行二分查找
//            int index = Arrays.binarySearch(arr, key);
//            if( index >= 0){
//                this.flag = "true";
//            }
//
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            //关闭文件资源
//            if(bf != null){
//                try {
//                    bf.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        this.starttime = simpleDateFormat.format(new Date());
        this.starttime = new Date();
        //进行二分查找
        int index = Arrays.binarySearch(arr, key);
        if (index >= 0) {
            int length = arr.length;
            int left = index - 1;
            this.Count++;
            //计算左边的次数
            while(left >= 0 && arr[left] == key){
                left--;
                this.Count++;
            }
            int right = index + 1;
            while (right < length && arr[right] == key){
                right++;
                this.Count++;
            }
            this.flag = "true";
        }
//         this.endtime = simpleDateFormat.format(new Date());
        this.endtime = new Date();
        this.gaptime = (endtime.getTime() - starttime.getTime()) + "ms";
    }
}
